package com.wiwf.model.security.service.impl;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.wiwf.model.bean.SysUserBean;
import com.wiwf.model.bean.SysUserVoto;
import com.wiwf.model.security.service.SysTokenService;
import com.wiwf.model.security.service.SysUserService;

/**
 * @author kehui
 */
@Service
public class CustomUserDetailsServiceImpl implements UserDetailsService  {
	
	@Resource
	private SysUserService userService;
	@Resource
	private SysTokenService tokenService;

	@Resource
	private HttpServletResponse response;
	@Resource
	private HttpServletRequest request;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		String token = tokenService.getToken(this.request);
		System.out.println("token ==== "+token);
		
		// 没有认证信息 token 是空的 就直接 调用
		if(ObjectUtils.isEmpty(token)) {
			SysUserBean user = userService.getUser(username);
			if (ObjectUtils.isEmpty(user.getName())) {
				System.out.println("认证失败");
				throw new UsernameNotFoundException("认证失败");
			} else {
				return userService.getUserTk(this.response,username);
			}
		} else {
			// 检查 是否是失效的，获取对应的用户信息
			SysUserVoto tokenUser = tokenService.getTokenUser(this.response, this.request);
			if (ObjectUtils.isEmpty(tokenUser) || ObjectUtils.isEmpty(tokenUser.getName())) {
				System.out.println("token ==== 无效，清理，触发重新认证");
				tokenService.delTokenUser(this.request);
				tokenService.delToken(this.response);
				throw new UsernameNotFoundException("用户未认证");
			} else {
				return userService.getUserTk(this.response, username);
			}
		}
	}
	
	private void def(String username) {
		/*
		String token = tokenService.getToken();
		System.out.println("token ==== "+token);
		
		// 没有认证信息 token 是空的 就直接 调用
		if(ObjectUtils.isEmpty(token)) {
			SysUserBean user = userService.getUser(username);
			if (ObjectUtils.isEmpty(user.getName())) {
				System.out.println("认证失败");
				throw new UsernameNotFoundException("认证失败");
			} else {
				return userService.getUserTk(username);
			}
		} else {
			// 检查 是否是失效的，获取对应的用户信息
			SysUserVoto tokenUser = tokenService.getTokenUser();
			if (ObjectUtils.isEmpty(tokenUser) || ObjectUtils.isEmpty(tokenUser.getName())) {
				System.out.println("token ==== 无效，清理，触发重新认证");
				tokenService.delTokenUser();
				tokenService.delToken();
				throw new UsernameNotFoundException("用户未认证");
			} else {
				return userService.getUserTk(username);
			}
		}
		*/
	}

}
